<template>
  <view class="game-container">
    <!-- 循环列表 -->
    <view class="card-list">
      <view v-for="(card, index) in groupForm.group1.concat(groupForm.group2)" :key="index" @click="flipCard(index, card)" class="card" :class="{ 'disabled': isCardMatched(card) }">
        <view v-if="!card.flipped" class="card-back"></view>  
        <view v-else class="bingo"><image :src="card.image" class="card-image" mode="aspectFit" /><text>{{card.name}}</text></view>
      </view>
    </view>
    <!-- 显示页码 -->
    <view class="page-number">
      {{ currentPage }} / {{ totalPages }}
    </view>
    <!-- 上一页、下一页和重置按钮 -->
    <view class="pagination-buttons">
      <button @click="prevPage" :disabled="currentPage === 1" class="pagination-button">上一页</button>
      <button @click="nextPage" :disabled="!isPageCompleted" class="pagination-button">下一页</button>
      <button @click="resetPage" class="pagination-button">重置</button>
    </view>
  </view>
</template>

<script>
import { selectGame, completeGame } from "../../../api/index";

export default {
  data() {
    // 定义卡片数据对象
    return {
      clickedItems: [], // 被点击过的数据
      groupForm: {
        group1: [],
        group2: []
      },
      cards: {
        GameDataList: [],
        // 第一组卡片
        group1: [
          // 第一张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/panada.png",
            audio: "https://www.afbeijing.net/static_resources/audio/sfx/starget.ogg",
            name: "apple",
            flipped: false
          },
          // 第二张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/xnk.png",
            audio: "https://www.afbeijing.net/static_resources/audio/sfx/cheer.ogg",
            name: "banana",
            flipped: false
          },
          // 第三张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/hhk.png",
            audio: "https://www.afbeijing.net/static_resources/audio/opening/opening.ogg",
            name: "cherry",
            flipped: false
          },
          // 第四张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/yyk.png",
            audio: "https://www.afbeijing.net/static_resources/audio/opening/kittyopening.ogg",
            name: "date",
            flipped: false
          }
        ],
        countNum: null, // 当前已成功8个
        // 第二组卡片
        group2: [
          // 第一张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/gj.png",
            audio: "https://www.afbeijing.net/static_resources/audio/sfx/starget.ogg",
            name: "apple",
            flipped: false
          },
          // 第二张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/yj.png",
            audio: "https://www.afbeijing.net/static_resources/audio/sfx/cheer.ogg",
            name: "banana",
            flipped: false
          },
          // 第三张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/jj.png",
            audio: "https://www.afbeijing.net/static_resources/audio/opening/opening.ogg",
            name: "cherry",
            flipped: false
          },
          // 第四张卡片
          {
            image: "https://www.afbeijing.net/static_resources/assets/jfpanada.png",
            audio: "https://www.afbeijing.net/static_resources/audio/opening/kittyopening.ogg",
            name: "date",
            flipped: false
          }
        ]
      },
      flippedCards: [],
      correctScores: 0,
      crsId: null,
      clsId: null,
      clsCrsId: null,
      isSameCard: false,
      gameId: null,
      flipCount: 0, // 新增的翻牌计数器
      matchedPairs: [], // 新增：记录匹配成功的卡片对
      currentPage: 1, // 当前页码
      totalPages: 3, // 总页数
      isPageCompleted: false, // 新增：当前页是否完成
      completedPages: [], // 新增：记录已完成的页面
      firstRowFlipped: false, // 新增：第一排是否有卡片被翻开
      secondRowFlipped: false, // 新增：第二排是否有卡片被翻开
      currentAudioCtx: null, // 新增：当前播放的音频上下文
    };
  },
  onLoad(e) {
    console.log(e, '2222');
    this.clsId = e.clsId;
    this.crsId = e.crsId;
    this.totalPages = e.Size;
    this.clsCrsId = Number(e.id);
    this.selectGameList();
    // 页面加载时调用洗牌方法
    this.shuffleCards();
  },
  onShow() {
    // var that=this
    //  uni.$u.on('update', function(res) {
    //  if(res.refresh){
    // console.log(res,'111')
    //  that.selectGameList()
    //  that.shuffleCards();
    // }
    //  })
  },
  onUnload() {
    // 页面卸载时停止所有音频
    this.stopAllAudio();
  },
  methods: {
    // 翻牌成功
    completeGame() {
      var jsonData = {
        clsId: this.clsId,
        clsCrsId: this.clsCrsId,
        crsId: this.crsId,
        tryNum: this.errorNo,
        gameId: Number(this.gameId)
      };
      completeGame(jsonData).then(response => {
        console.log(response);
        if (response.code === 0) {
          var _this = this;
          uni.showLoading({
            title: '加载中'
          });
          setTimeout(function () {
            // 隐藏loading
            uni.hideLoading();
            uni.showModal({
              title: '提示',
              showCancel: false,
              content: '恭喜你完成了本关！',
              success: function (res) {
                if (res.confirm) {
                  _this.isPageCompleted = true;
                  _this.completedPages.push(_this.currentPage);
                  console.log(_this.completedPages.length, _this.totalPages);
                  if (_this.completedPages.length === Number(_this.totalPages)) {
                    uni.redirectTo({
                      url: '/src/views/pageStudy/common/huodejifen/index?showButton=true&jifen=' + '5'
                    });
                  }
                }
              }
            });
          }, 1000);
        } else {
          //
        }
      });
    },
    // 查询翻牌游戏
    selectGameList() {
      // this.clsCrsId=494
      // this.crsId='ag300-cls301-crs001'
      var jsonData = {
        clsCrsId: this.clsCrsId,
        crsId: this.crsId,
        pageNum: this.currentPage
      };
      selectGame(jsonData).then(response => {
        if (response.code === 0) {
          this.groupForm = response.data;
          this.gameId = response.data.gameId;
          this.isPageCompleted = false;
          this.matchedPairs = [];
          this.flipCount = 0;
          this.clickedItems = [];
          this.groupForm.group1.forEach(card => card.flipped = false);
          this.groupForm.group2.forEach(card => card.flipped = false);
          this.firstRowFlipped = false; // 重置第一排状态
          this.secondRowFlipped = false; // 重置第二排状态
          this.stopAllAudio(); // 重置页面时停止所有音频
        } else {
          uni.$u.toast(response.msg);
        }
      }).catch(errors => {
        // uni.$u.toast(errors);
      });
    },
    shuffleCards() {
      // 洗牌逻辑，打乱第一组卡片的顺序
      for (let i = this.cards.group1.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [this.cards.group1[i], this.cards.group1[j]] = [this.cards.group1[j], this.cards.group1[i]];
      }
      // 洗牌逻辑，打乱第二组卡片的顺序
      for (let i = this.cards.group2.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [this.cards.group2[i], this.cards.group2[j]] = [this.cards.group2[j], this.cards.group2[i]];
      }
    },
    // 点击事件处理函数
    handleClick(item) {
      // 检查 item 是否已经在 clickedItems 中
      this.clickedItems.push(item);
      let uniqueArr = Array.from(new Set(this.clickedItems.map(JSON.stringify)), JSON.parse);
      console.log(uniqueArr.length);
      this.countNum = uniqueArr.length;
    },
    // 判断卡片是否已经配对成功
    isCardMatched(card) {
      return this.matchedPairs.some(pair => pair.includes(card));
    },
    flipCard(index, item) {
      // 判断是否是第一排卡片
      const isFirstRow = index < 4;

      // 检查卡片是否已经配对成功
      if (this.isCardMatched(item)) {
        return; // 阻止翻牌操作
      }

      // 检查是否可以翻牌
      if (!isFirstRow && !this.firstRowFlipped) {
        // 第二排卡片且第一排没有卡片被翻开
        uni.showToast({
          title: '请先翻开第一排的一张卡片',
          icon: 'none'
        });
        return; // 阻止翻牌操作
      }

      // 检查是否已经翻开第一排的卡片，且当前点击的是第一排的卡片
      if (this.firstRowFlipped && isFirstRow) {
        uni.showToast({
          title: '请从第二行选择卡片进行配对',
          icon: 'none'
        });
        return; // 阻止翻牌操作
      }

      // 根据点击的索引获取对应的卡片
      const card = this.groupForm.group1.concat(this.groupForm.group2)[index];
      if (!card.flipped) {
        this.handleClick(card);
      }
      // 将卡片设置为已翻开状态
      card.flipped = true;

      // 更新行列状态
      if (isFirstRow) {
        this.firstRowFlipped = true;
      } else {
        this.secondRowFlipped = true;
      }

      // 实现第二排第五条数据开始点击不播放语音的功能
      if (index < 4) {
        // 第一排数据（索引0 - 3）继续播放语音
        this.playCardAudio(card.audio);
      } else {
        // 第二排数据（索引4 - 7）不播放语音
        console.log(`第${index + 1}张卡片点击，不播放语音`);
      }

      // 将翻开的卡片添加到已翻开卡片数组中
      this.flippedCards.push(card);
      this.flipCount++; // 每次翻牌计数器加1

      if (this.flippedCards.length === 2) {
        // 判断两张卡片是否分别来自 group1 和 group2
        const isFromDifferentGroups = (this.groupForm.group1.includes(this.flippedCards[0]) && this.groupForm.group2.includes(this.flippedCards[1])) ||
          (this.groupForm.group2.includes(this.flippedCards[0]) && this.groupForm.group1.includes(this.flippedCards[1]));

        // 判断两张翻开的卡片的名称是否相同
        this.isSameCard = this.flippedCards[0].name === this.flippedCards[1].name;

        if (isFromDifferentGroups && this.isSameCard) {
          // 两张卡片来自不同组且名称相同，记录匹配成功的卡片对
          this.matchedPairs.push([this.flippedCards[0], this.flippedCards[1]]);

          // 停止当前播放的所有音频
          this.stopAllAudio();

          this.playCorrectAudio();

          // 检查是否所有匹配都已完成
          if (this.matchedPairs.length === this.groupForm.group1.length) {
            this.completeGame();
          }
        } else {
          // 若不同，延迟2秒将这两张卡片翻转回去
          if (this.flippedCards[0] && this.flippedCards[1]) {
            this.flippedCards[0].flipped = false;
            this.flippedCards[1].flipped = false;
          }
          this.playErrorAudio();
        }
        // 清空已翻开卡片数组
        this.flippedCards = [];

        // 重置行列状态，允许下一轮翻牌
        this.firstRowFlipped = false;
        this.secondRowFlipped = false;
      }
    },
    playCardAudio(audioPath) {
      // 停止当前播放的音频
      this.stopAllAudio();

      // 创建新的音频上下文
      const audioCtx = uni.createInnerAudioContext();
      this.currentAudioCtx = audioCtx;

      // 设置音频源
      audioCtx.src = audioPath;

      // 播放音频
      audioCtx.play();

      // 监听音频播放结束
      audioCtx.onEnded(() => {
        this.currentAudioCtx = null;
      });

      // 监听音频播放错误
      audioCtx.onError(() => {
        this.currentAudioCtx = null;
      });
    },
    playCorrectAudio() {
      // 停止当前播放的所有音频
      this.stopAllAudio();

      // 创建正确提示音的音频上下文
      const correctAudioCtx = uni.createInnerAudioContext();
      this.currentAudioCtx = correctAudioCtx;

      correctAudioCtx.src = "https://www.afbeijing.net/static_resources/audio/right.mp3";
      correctAudioCtx.play();

      // 监听音频播放结束
      correctAudioCtx.onEnded(() => {
        this.currentAudioCtx = null;
      });

      // 监听音频播放错误
      correctAudioCtx.onError(() => {
        this.currentAudioCtx = null;
      });
    },
    playErrorAudio() {
      // 停止当前播放的所有音频
      this.stopAllAudio();

      // 创建错误提示音的音频上下文
      const errorAudioCtx = uni.createInnerAudioContext();
      this.currentAudioCtx = errorAudioCtx;

      errorAudioCtx.src = "https://www.afbeijing.net/static_resources/audio/wrong.mp3";
      errorAudioCtx.play();

      // 监听音频播放结束
      errorAudioCtx.onEnded(() => {
        this.currentAudioCtx = null;
      });

      // 监听音频播放错误
      errorAudioCtx.onError(() => {
        this.currentAudioCtx = null;
      });
    },
    stopAllAudio() {
      // 停止当前播放的音频
      if (this.currentAudioCtx) {
        this.currentAudioCtx.stop();
        this.currentAudioCtx.destroy();
        this.currentAudioCtx = null;
      }
    },
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.selectGameList();
      }
    },
    // 下一页
    nextPage() {
      console.log(this.isPageCompleted, this.currentPage, this.totalPages);
      if (this.isPageCompleted && this.currentPage < Number(this.totalPages)) {
        this.currentPage++;
        this.selectGameList();
      } else if (this.isPageCompleted && this.currentPage === Number(this.totalPages)) {
        uni.redirectTo({
          url: '/src/views/pageStudy/common/huodejifen/index?showButton=false'
        });
      } else {
        uni.showToast({
          title: '当前页未完成，无法跳转',
          icon: 'none'
        });
      }
    },
    // 重置当前页
    resetPage() {
      this.currentPage = 1;
      this.selectGameList();
      // 重置卡片状态
      this.groupForm.group1.forEach(card => card.flipped = false);
      this.groupForm.group2.forEach(card => card.flipped = false);
      this.flippedCards = [];
      this.matchedPairs = [];
      this.flipCount = 0;
      this.clickedItems = [];
      this.isPageCompleted = false;
      this.completedPages = [];
      this.firstRowFlipped = false; // 重置第一排状态
      this.secondRowFlipped = false; // 重置第二排状态
      this.stopAllAudio(); // 重置页面时停止所有音频
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/static/styles/variables.scss";

/* 去除body的默认边距和滚动条 */
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
.bingo {
  width: 100%;
  height: 100%;
  position: relative;
  image {
    width: 100%;
    height: 100%;
  }
  text {
    position: absolute;
    top: 0%;
    left: 0;
    padding: 3rpx;
    background: rgba(254,180,7,0.8);
    text-align: center;
    // width: 100%;
  }
}
.game-container {
  padding: 20rpx;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  /* 容器宽度设置为100vw，高度设置为100vh */
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  position: relative;
}

.card-list {
  flex: 0 0 84%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.card {
  /* 使用更精确的百分比计算卡片宽度和高度，保持4:3的比例 */
  width: 18vw;
  height: 35vw;
  max-height: 35vh;
  margin: 1%;
  border-radius: 10rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
  position: relative;
  transition: transform 0.5s ease;
}

.card-back {
  width: 100%;
  height: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  background: url(#{$bgImageUrl}/assets/bg_1.png) center no-repeat;
  // background: url('https://www.afbeijing.net/youxiimage/bg_1.png') no-repeat;
  background-size: 70% 100%;
  background-color: #FFB607;
  border-radius: 10rpx;
}
    // display: flex;
    // align-items: center;
    // justify-content: center;
.card-image {
  width: 100%;
  // height: 100%;
}

.card.flipped {
  transform: rotateY(180deg);
}

.card.disabled {
  pointer-events: none; /* 禁止点击事件 */
  opacity: 0.8; /* 可选：设置透明度以视觉上表示禁用状态 */
}

.page-number {
  position: absolute;
  top: 15rpx;
  right: 5%;
  font-size: 20rpx;
  z-index: 1;
  color: #FF8106;
}

.pagination-buttons {
  flex: 0 0 13%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
}

.pagination-button {
  width: 100%; /* 设置按钮宽度为100%，使其大小一致 */
  height: 35rpx; /* 设置按钮高度 */
  line-height: 35rpx;
  background-color: #FF8106; /* 设置按钮颜色 */
  color: white; /* 设置按钮文字颜色 */
  border: none; /* 去除按钮边框 */
  border-radius: 5rpx; /* 设置按钮圆角 */
  font-size: 16rpx; /* 设置按钮文字大小 */
}
</style>